package com.ruoyi.modules.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.modules.domain.TopUpRule;
import com.ruoyi.modules.domain.vo.PayPayInfoVO;
import com.ruoyi.modules.service.INumRecordService;
import com.ruoyi.modules.service.ITopUpRuleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.modules.mapper.PayPayInfoMapper;
import com.ruoyi.modules.domain.PayPayInfo;
import com.ruoyi.modules.service.IPayPayInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
 * 支付信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-01-22
 */
@Service
@Slf4j
public class PayPayInfoServiceImpl extends ServiceImpl<PayPayInfoMapper, PayPayInfo> implements IPayPayInfoService {

    @Autowired
    private ITopUpRuleService topUpRuleService;
    @Autowired
    private INumRecordService numRecordService;


    /**
     * 初始化订单
     * @return
     */
    private PayPayInfo generatePayPayInfo(){
        PayPayInfo payPayInfo = new PayPayInfo();
        //支付状态：0->待付款；
        payPayInfo.setPaymentStatus(0);
        //系统订单编号
        payPayInfo.setTradeNo(getOrderNumber());
        return payPayInfo;
    }

    public static String getOrderNumber() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = df.format(new Date());
        String randomString = RandomStringUtils.randomNumeric(6);
        return time + randomString;
    }

    @Override
    public PayPayInfo payDataNum(Long agentUserId, Long topUpRuleId) {
        PayPayInfo payPayInfo = generatePayPayInfo();
        TopUpRule topUpRule = topUpRuleService.getById(topUpRuleId);


        //所付实际现金
        BigDecimal payCash = topUpRule.getMoney();


        payPayInfo.setUserId(agentUserId);
        //微信支付
        payPayInfo.setPayType(1);
        //所付实际现金
        payPayInfo.setPayCash(payCash);


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num", topUpRule.getNum());
        payPayInfo.setBusinessDetails(jsonObject.toJSONString());

        payPayInfo.setPayClass(1);
        payPayInfo.setSubject("购买次数 (" + topUpRule.getNum() + "次)");


        this.save(payPayInfo);
        return payPayInfo;
    }

    @Override
    public boolean payCallback(String transaction_id, String out_trade_no) {
        log.info("订单编号 ： " + out_trade_no);
        boolean success = false;

        PayPayInfo payPayInfo =  this.getOne(new LambdaQueryWrapper<PayPayInfo>().eq(PayPayInfo::getTradeNo, out_trade_no).last("limit 1"));
        if (payPayInfo == null){
            log.error("payPayInfo 为空");
            return false;
        }
        if (payPayInfo.getPaymentStatus() == 1){
            log.error("已经支付成功回调过");
            return false;
        }

        log.info("payPayInfo.getPayClass()支付类型 为 ：" + payPayInfo.getPayClass());
        if (1 == payPayInfo.getPayClass()){
            //支付类型：0->购买次数；
            log.info("支付回调 - 购买次数");
            JSONObject jsonObject = JSON.parseObject(payPayInfo.getBusinessDetails());
            Long num = jsonObject.getLong("num");
            success = numRecordService.addNum(payPayInfo.getUserId(), num, "在线充值");
        } else {
            log.error("payPayInfo.getPayClass()支付类型 为 ：" + payPayInfo.getPayClass() + "  不匹配！！！");
        }




        if (success) {
            log.info("支付回调 - 回调付费成功");
            //更新订单状态
            this.update(new LambdaUpdateWrapper<PayPayInfo>()
                    .set(PayPayInfo::getPaymentStatus, 1)
                    .set(StringUtils.isNotEmpty(transaction_id), PayPayInfo::getTransactionId,transaction_id)
                    .eq(PayPayInfo::getId, payPayInfo.getId())
            );
        } else {
            log.error("支付回调 - 回调付费失败！！！");
        }
        return success;
    }

    @Override
    public List<PayPayInfoVO> listPayPayInfo() {
        return baseMapper.listPayPayInfo();
    }
}
